package com.loong.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.loong.mapper.PermissionMapper;
import com.loong.mapper.RoleMapper;
import com.loong.mapper.UserMapper;
import com.loong.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 查询用户权限列表
        List<String> strings = permissionMapper.selectListByUid(user.getUid());

        // 查询用户角色列表
        List<String> roles = roleMapper.selectListByUid(user.getUid());
        for (String role : roles) {
            strings.add("ROLE_"+role); // 添加角色前缀 ROLE_
        }

        // 封装用户信息，返回UserDetails实现类
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                AuthorityUtils.createAuthorityList(strings)
        );
        return userDetails;
    }
}